<template>
	<view class="container">
		<view class="content">	
			<view class="sub-content" @click="blueOpenLock()">
				<view class="sub-title">
					蓝牙开锁
				</view>	
				<view class="sub-icon">
					>
				</view>
			</view>		
			<view class="sub-content" @click="remoteOpenLock()">
				<view class="sub-title">
					远程开锁
				</view>	
				<view class="sub-icon">
					>
				</view>
			</view>				
		</view>		
	</view>
</template>

<script>
	import {		
		sendOpenRec,
		getOpenLockCmd
	} from '@/api/lock.js'
	import {
		remoteUnlock
	} from '@/api/mine.js'
	import util from '@/utils/util.js';
	import bleUtils from '@/utils/BleUtils.js';
	export default {
		data() {
			return {
				lockNo:'',
				roomName:'1105室',
				mobile:this.$userInfo.mobile,
				type: 0,//类型 0 远程开锁 1 远程关锁 2 远程常开
				replyMsg: '', // 命令的回复数据
				cmdLen: 0, // 命令的字节长度
				recordId: '',
				lockMac:'',// 蓝牙名称跟mac 一样
				bleName:'',
			};
		},
		onLoad(option) {	
			this.roomName = option.roomName;
			this.lockNo = option.lockNo;
			this.lockMac = option.mac;
			this.bleName = this.lockMac;
			this.mac = util.strInsert(this.lockMac, 2);
			wx.setNavigationBarTitle({
				title: this.roomName,
			})
		},
		onUnload() {
			// 关闭蓝牙连接
			bleUtils.closeBLEConnection();
			// 关闭蓝牙适配器
			bleUtils.closeBluetoothAdapter();
		},
		methods: {	
			//远程开锁
			async remoteOpenLock(){
				const param = {
					mobile: this.mobile,	
					type: this.type,
					lockNo: this.lockNo,				
				}				
				let res = await remoteUnlock(param);
				if (res.statecode === '0') {
					util.toast('远程开锁成功！');
				}
				else 
				{
					util.toast(res.statemsg);
				}
			},
			// 执行蓝牙开锁
			async blueOpenLock() {
				try {
					util.loading('开锁中...');
					this.replyMsg='';
					// 打开蓝牙适配器
					await bleUtils.openBluetoothAdapter();
					let resp = await getOpenLockCmd({
						lockNo: this.lockNo,
						isOpen: true,
						mobile: this.mobile
					});
					if (resp && resp.statecode == '0' && resp.data.taskMessage) {
						await bleUtils.waitBleConnAndNotify(this.bleName, this.formatLockMac);
						// 监听当特征值发生变化的回调
						bleUtils.onBLECharacteristicValueChange((res) => {
							this.receiveBleData(res)
						});
						const cmdMsg = resp.data.taskMessage;
						this.recordId = resp.data.recordId;
						const cmd_buffer = bleUtils.myStringtoHex(cmdMsg);
						this.sendPacket(cmd_buffer);
					} else {
						util.infotip('获取开锁命令失败!');
					}
					util.hideLoading();
					
				} catch (err) {
					console.log('bluetooth err--->', err)
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
			// 发送数据包给蓝牙设备
			async sendPacket(cmdData) {
				try {
					console.log('sendPacket:cmdData-------', cmdData)
					const unit8Array_data = new Uint8Array(cmdData);
					const data = unit8Array_data.buffer;
					console.log('sendPacket:data--------', data)
					await bleUtils.writeBLECharacteristicValue(data);
				} catch (err) {
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBLEConnection();
				}
			},
			async receiveBleData(res) {
				try {
					this.replyMsg += res;
					console.log('replyMsg res==>', this.replyMsg)
					const header = res.substr(0, 4).toUpperCase();
					if (header == '55AA') {
						this.cmdLen = parseInt(res.substr(4, 4), 16) * 2 + 8;
					} else {
						console.log('replyMsg.length', this.replyMsg.length, ' cmdLen', this.cmdLen)
						if (this.replyMsg.length == this.cmdLen) {
							const resp = await sendOpenRec({
								'lockNo': this.lockNo,
								'recordId': this.recordId,
								'replyMessage': this.replyMsg.toUpperCase(),
								'replyCode': '00'
							})
							util.hideLoading();
							if (resp && resp.statecode == '0') {
								util.toast('开锁成功!');
							} else {
								util.toast('上传记录失败!');
							}
						}
					}
				} catch (err) {
					console.log(err)
					util.hideLoading();
				}
			
			},		
		}
	}
</script>

<style lang="less">
	.container {
		background-color: #F8F8FA;
		font-size: 32rpx;		

		.content {
			position: absolute;
			left: 0rpx;
			right: 0rpx;
			bottom: 0rpx;
			top: 0rpx;
			padding-left: 32rpx;
			padding-right: 32rpx;
			
			.sub-content{
				height: 100rpx;
				width: 100%;
				background: #FFFFFF;
				border-radius: 16rpx;
				margin-top: 20rpx;
				display: flex;
				align-items: center
			}	
			
			.sub-title{
				width: 50%;
				font-size: 32rpx;
				font-weight: 400;
				color: #1F2642;
				padding-left: 24rpx;
			}
			.sub-icon{
				width: 50%;
				color:#000000;
				opacity: 0.5;
				text-align: right;
				padding-right: 30rpx;
			}
			
		}
	}
</style>